package com.zhuhjay.system.filter;

import com.zhuhjay.common.domain.ResponseJson;
import com.zhuhjay.common.enums.HttpCode;
import com.zhuhjay.common.servlet.RequestWrapper;
import com.zhuhjay.common.utils.JwtUtils;
import com.zhuhjay.common.utils.ServletUtils;
import com.zhuhjay.system.domain.entity.User;
import com.zhuhjay.system.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 通过过滤器来进行token的解析
 * @author ZhuHJay
 * @date 2022/3/21 21:26
 */
@Slf4j
public class AuthTokenFilter implements Filter {

    private final IUserService userService;

    public AuthTokenFilter(IUserService userService){
        this.userService = userService;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String token = req.getHeader("Authorization");
        // 如果存在token那么就去进行token解析
        if( token != null && StringUtils.hasLength(token.trim()) && !"null".equals(token.trim()) ){
            String username;
            try {
                username = JwtUtils.verifyToken(token);
            } catch (Exception e) {
                ServletUtils.writeJson(res, ResponseJson.error(HttpCode.LOGIN_FAILURE));
                return;
            }
            User userInfo = userService.getUserByUsername(username);
            if( userInfo != null ){
                RequestWrapper requestWrapper = new RequestWrapper(req);
                requestWrapper.addParameters("id", userInfo.getId());
                requestWrapper.addParameters("username", userInfo.getUsername());
                chain.doFilter(requestWrapper, response);
            }else{
                ServletUtils.writeJson(res, ResponseJson.error(HttpCode.LOGIN_FAILURE));
            }
        }
        // 不存在token就放行, 可能是静态资源访问
        else{
            chain.doFilter(request, response);
        }
    }

}
